package com.guimin.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.guimin.common.util.SpringContextUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 重复拦截器
 *
 * @author hzy
 */
public class RepeatInterceptor extends HandlerInterceptorAdapter {
    /**
     * redis服务
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws IOException {
        /*String flowId = request.getParameter("flowId");
        if (flowId==null){
            return true;
        }*/
        if (redisTemplate == null) {
            redisTemplate = (RedisTemplate<String, Object>) SpringContextUtils.getBean("redisTemplate");
        }
        String token = request.getHeader("token");
        Object obj = redisTemplate.opsForValue().get("Lock" + token);
        String uri = request.getRequestURI();
        if (uri.equals(obj)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;content-type=UTF-8");
            HashMap<Object, Object> map = new HashMap<>(2);
            map.put("success", false);
            map.put("message", "请勿频繁操作");
            response.getWriter().print(JSON.toJSONString(map));
            return false;
        }
        redisTemplate.opsForValue().set("Lock" + token, uri, 3, TimeUnit.SECONDS);
        return true;
    }

}
